package service

import (
	"GINCHAT/modules"
	"GINCHAT/utils"
	"fmt"
	"github.com/asaskevich/govalidator"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"math/rand"
	"net/http"
	"strconv"
	"time"
)

func GetUserList(c *gin.Context) {
	userBasics := make([]*modules.UserBasic, 10)
	userBasics = modules.GetUserList()
	c.JSON(200, gin.H{
		"code":    0, // 0成功 -1失败
		"message": "获取用户成功！",
		"data":    userBasics,
	})

}

// @Summary 新增用户
// @Tags 用户模块
// @param name query string false "用户名"
// @param password query string false "密码"
// @param repassword query string false "确认密码"
// @Success 200 {string} json {"code","message"}
// @Router /user/createUser [get]
func CreateUser(c *gin.Context) {

	user := modules.UserBasic{}
	user.Name = c.Query("name")
	password := c.Query("password")
	repassword := c.Query("repassword")

	salt := fmt.Sprintf("%06d", rand.Int31())

	data := modules.FindUserByName(user.Name)
	if data.Name != "" {
		c.JSON(200, gin.H{
			"code":    -1, // 0成功 -1失败
			"message": "用户名已经注册",
			"data":    "",
		})
		return
	}

	if password != repassword {
		c.JSON(200, gin.H{
			"code":    -1, // 0成功 -1失败
			"message": "两次密码不一致",
			"data":    "",
		})

	} else {
		//user.PassWord = password
		user.PassWord = utils.MakePassword(password, salt)
		user.Salt = salt
		modules.CreateUser(user)
		c.JSON(200, gin.H{
			"code":    0, // 0成功 -1失败
			"message": "用户新建成功",
			"data":    "",
		})

	}

}

// @Summary 删除用户
// @Tags 用户模块
// @param id query string false "用户id"
// @Success 200 {string} json {"code","message"}
// @Router /user/deleteUser [get]
func DeleteUser(c *gin.Context) {

	user := modules.UserBasic{}

	user.ID = utils.StringToUint(c.Query("id"))

	modules.DeleteUser(user)

	c.JSON(200, gin.H{
		"code":    0, // 0成功 -1失败
		"message": "用户删除成功",
		"data":    "",
	})
}

// UpdateUser
// @Summary 修改用户
// @Tags 用户模块
// @param id formData string false "id"
// @param name formData string false "name"
// @param password formData string false "password"
// @param phone formData string false "phone"
// @param email formData string false "email"
// @Success 200 {string} json{"code","message"}
// @Router /user/updateUser [post]
func UpdateUser(c *gin.Context) {
	user := modules.UserBasic{}
	id, _ := strconv.Atoi(c.PostForm("id"))
	user.ID = uint(id)
	user.Name = c.PostForm("name")
	user.PassWord = c.PostForm("password")
	user.Phone = c.PostForm("phone")
	user.Email = c.PostForm("email")
	fmt.Println("update :", user)
	_, err := govalidator.ValidateStruct(user)
	if err != nil {
		fmt.Println(err)

		c.JSON(200, gin.H{
			"code":    -1, // 0成功 -1失败
			"message": "修改参数不匹配！",
			"data":    "",
		})
	} else {

		c.JSON(200, gin.H{
			"code":    0, // 0成功 -1失败
			"message": "修改用户成功！！",
			"data":    "",
		})
	}
}

// GetUserList
// @Summary 用户登录
// @Tags 用户模块
// @param name query string false "用户名"
// @param password query string false "密码"
// @Success 200 {string} json{"code","message"}
// @Router /user/findUserByNameAndPwd [get]
func FindUserByNameAndPwd(c *gin.Context) {
	data := modules.UserBasic{}
	name := c.Query("name")
	password := c.Query("password")
	user := modules.FindUserByName(name)
	if user.Name == "" {

		c.JSON(200, gin.H{
			"code":    -1, // 0成功 -1失败
			"message": "该用户不存在！",
			"data":    "",
		})

		return
	}

	flag := utils.ValidPassword(password, user.Salt, user.PassWord)
	if !flag {

		c.JSON(200, gin.H{
			"code":    -1, // 0成功 -1失败
			"message": "密码不正确！",
			"data":    "",
		})

		return
	}
	pwd := utils.MakePassword(password, user.Salt)
	data = modules.FindUserByNameAndPwd(name, pwd)

	c.JSON(200, gin.H{
		"code":    0, // 0成功 -1失败
		"message": "登陆成功！",
		"data":    data,
	})
}

var upGrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func SendMsg(c *gin.Context) {
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer ws.Close()
	MsgHandler(c, ws)
}
func MsgHandler(c *gin.Context, ws *websocket.Conn) {
	for {
		msg, err := utils.Subscribe(c, utils.PublishKey)
		if err != nil {
			fmt.Println(" MsgHandler 发送失败", err)
		}
		tm := time.Now().Format("2006-01-02 15:04:05")
		m := fmt.Sprintf("[ws][%s]:%s", tm, msg)
		err = ws.WriteMessage(1, []byte(m))
		if err != nil {
			log.Fatalln(err)
		}
	}
}
